using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.Routings.Commands;

/// <summary>
/// 工艺路线更新命令。
/// </summary>
public sealed record UpdateRoutingCommand(long Id, ProcRoutingDto Routing) : IRequest<IResult<bool>>;

internal sealed class UpdateRoutingCommandHandler(IRepository<ProcRouting> repo) : IRequestHandler<UpdateRoutingCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateRoutingCommand request, CancellationToken cancellationToken)
    {
        // 检查产品在此工艺路线是否唯一
        // 目前设定：同一产品在同一生产线中必须唯一（启用状态）
        if (await repo.IsAnyAsync(m => m.LineId == request.Routing.LineId
            && m.ProductId == request.Routing.ProductId
            && m.Status == EnabledStatusEnum.Enabled
            && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("该产品在此生产线中已存在可用的工艺路线");
        }

        var routing = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (routing == null)
        {
            return Result.Failure("未找到要更新的工艺路线");
        }

        routing.RoutingName = request.Routing.RoutingName;
        routing.LineId = request.Routing.LineId;
        routing.ProductId = request.Routing.ProductId;
        routing.IsMaster = request.Routing.IsMaster;
        routing.Order = request.Routing.Order;
        routing.Remark = request.Routing.Remark;
        routing.Status = request.Routing.Status;

        var ok = await repo.UpdateAsync(routing, m => new
        {
            m.RoutingName,
            m.LineId,
            m.ProductId,
            m.IsMaster,
            m.Order,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
